import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { isArray } from '@pureadmin/utils'
import { useUserStore, useCommonStore } from '@/stores'
import { multiplication } from '@pureadmin/utils'
import { addCartApi, getCartListApi, delCartApi, editCartApi } from '@/api'
import { message } from 'ant-design-vue'

export const useCartStore = defineStore(
  'cart',
  () => {
    // 购物车列表根据区域区分，且购物车中的数据未登录时也可以购买商品，
    // 未登录时也可以加入购物车，登录成功时需要将其上传至服务器
    // 购物车列表
    const cartList = ref({
      // 登录状态：如果没有登录且list中有数据，登陆成功后需要上传至服务器。
      isLogin: false,
    })

    // 购物车信息
    const cartInfo = computed(() => {
      const { selectedGame, selectedArea } = useCommonStore()
      const game_area = selectedGame.key + '_' + selectedArea.key
      let list = cartList.value[game_area] || []
      let count = list.reduce((acc, cur) => acc + cur.num, 0)
      let total = list.reduce((acc, cur) => acc + multiplication(cur.num, Number(cur.price), 2), 0)
      return {
        list,
        count,
        total,
      }
    })

    // 未登录时添加至购物车
    const addNoLoginCart = (game_area, goods) => {
      // console.log(game_area, goods)
      // 判断当前游戏区域内购物车中是否有商品
      // 判断是否为数组 如果为数组则直接添加
      const bool = isArray(cartList.value[game_area])
      // 有商品
      if (bool) {
        // 判断是否已经存在该商品
        const isCart = cartList.value[game_area].some((i) => i.sku === goods.sku)
        if (isCart) {
          // 如果存在则数量相加
          cartList.value[game_area].forEach((i) => {
            if (i.sku === goods.sku) {
              i.num += goods.num
            }
          })
          return
        }
        cartList.value[game_area].push(goods)
      } else {
        // 无商品
        cartList.value[game_area] = [goods]
      }
    }

    // 登录成功后上传购物车数据
    const uploadCart = () => {
      const { isLogin } = cartList.value
      const len = Object.keys(cartList.value)
      if (!isLogin && len.length !== 1) {
        const index = len.findIndex((i) => i === 'isLogin')
        // 在获取到的游戏区域列表中 删除 isLogin 这个键
        len.splice(index, 1)
        // 上传购物车数据
        len.forEach((key) => {
          const game_area = key.split('_')
          // 判断区域中是否有商品
          if (cartList.value[key].length) {
            // 有的话循环上传至购物车
            cartList.value[key].forEach(async (item) => {
              const params = {
                game_id: game_area[0],
                area_id: game_area[1],
                sku: item.sku,
                num: item.num,
              }
              await addCartApi(params)
            })
            cartList.value[key] = []
          }
        })
      }
      cartList.value.isLogin = true
    }

    // 获取购物车数据
    const getCartList = () => {
      const { token } = useUserStore()
      const { selectedGame, selectedArea } = useCommonStore()
      if (!token) return
      const params = {
        game_id: selectedGame.key,
        area_id: selectedArea.key,
      }
      getCartListApi(params).then((res) => {
        // console.log(res)
        cartList.value.isLogin = true
        cartList.value[selectedGame.key + '_' + selectedArea.key] = res.goods
      })
    }

    // 修改购物车数量
    const editCart = (sku, num) => {
      const { token } = useUserStore()
      const { selectedGame, selectedArea } = useCommonStore()
      const game_area = selectedGame.key + '_' + selectedArea.key
      let list = cartList.value[game_area] || []
      if (token) {
        const params = {
          sku,
          game_id: selectedGame.key,
          area_id: selectedArea.key,
          num,
        }
        editCartApi(params).then(() => {
          list.forEach((i) => {
            if (i.sku === sku) {
              i.num = num
            }
          })
          message.success('Edit Success')
        })
      } else {
        list.forEach((i) => {
          if (i.sku === sku) {
            i.num = num
          }
        })
      }
    }

    // 删除商品
    const delCartGoods = (sku) => {
      const { token } = useUserStore()
      const { selectedGame, selectedArea } = useCommonStore()
      const game_area = selectedGame.key + '_' + selectedArea.key
      let list = cartList.value[game_area] || []
      if (token) {
        const params = {
          sku,
          game_id: selectedGame.key,
          area_id: selectedArea.key,
        }
        delCartApi(params).then(() => {
          list.forEach((i, index) => {
            if (i.sku === sku) {
              list.splice(index, 1)
            }
          })
          message.success('Del Success')
        })
      } else {
        list.forEach((i, index) => {
          if (i.sku === sku) {
            list.splice(index, 1)
          }
        })
      }
    }

    // 清空购物车
    const clearCart = () => {
      const { selectedGame, selectedArea } = useCommonStore()
      const game_area = selectedGame.key + '_' + selectedArea.key
      cartList.value[game_area] = []
    }

    return {
      cartInfo,
      cartList,
      addNoLoginCart,
      editCart,
      uploadCart,
      getCartList,
      delCartGoods,
      clearCart,
    }
  },
  {
    persist: true,
  },
)
